import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import * as api from '../utils/api';
import { TournamentState, Match, Team, TournamentConfig } from '../types';

const BracketPage: React.FC = () => {
  const navigate = useNavigate();
  const [tournamentState, setTournamentState] = useState<TournamentState | null>(null);
  const [tournamentConfig, setTournamentConfig] = useState<TournamentConfig | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadTournamentStatus();
  }, []);

  const loadTournamentStatus = async () => {
    try {
      setLoading(true);
      const [statusResponse, configResponse] = await Promise.all([
        api.getTournamentStatus(),
        api.getTournamentConfig()
      ]);

      if (statusResponse.success && statusResponse.tournament_state) {
        setTournamentState(statusResponse.tournament_state);
      }

      if (configResponse.success && configResponse.config) {
        setTournamentConfig(configResponse.config);
      }

      setError(null);
    } catch (err) {
      setError('加载比赛状态失败');
      console.error('加载比赛状态失败:', err);
    } finally {
      setLoading(false);
    }
  };

  const getMatchesByRound = (round: string): Match[] => {
    if (!tournamentState || !tournamentState.matches) return [];
    return tournamentState.matches.filter(match => match.round === round);
  };

  const getRevivalTeams = (): Team[] => {
    if (!tournamentState) return [];
    // 从新的数据结构中获取复活队伍
    if (tournamentState.round_results && tournamentState.round_results.round1_revival) {
      return tournamentState.round_results.round1_revival.advanced || [];
    }
    // 兼容旧的数据结构
    return (tournamentState as any).revival_teams || [];
  };

  const getRound1Eliminated = (): Team[] => {
    if (!tournamentState) return [];
    // 从新的数据结构中获取第一轮淘汰队伍
    if (tournamentState.round_results && tournamentState.round_results.round1_main) {
      return tournamentState.round_results.round1_main.eliminated || [];
    }
    // 兼容旧的数据结构
    return (tournamentState as any).round1_eliminated || [];
  };

  const getRound1Advanced = (): Team[] => {
    if (!tournamentState) return [];
    // 从新的数据结构中获取第一轮晋级队伍
    if (tournamentState.round_results && tournamentState.round_results.round1_main) {
      return tournamentState.round_results.round1_main.advanced || [];
    }
    // 兼容旧的数据结构
    return (tournamentState as any).round1_advanced || [];
  };

  const TeamCard: React.FC<{ 
    team: Team | null; 
    isWinner?: boolean; 
    isLoser?: boolean;
    className?: string;
  }> = ({ team, isWinner, isLoser, className = '' }) => {
    if (!team) {
      return (
        <div className={`bg-gray-600 text-gray-300 px-3 py-2 rounded text-center ${className}`}>
          待定
        </div>
      );
    }

    let bgColor = 'bg-blue-600';
    if (isWinner) bgColor = 'bg-green-600';
    if (isLoser) bgColor = 'bg-gray-600';

    return (
      <div className={`${bgColor} text-white px-3 py-2 rounded text-center ${className}`}>
        <div className="font-semibold">{team.name}</div>
        <div className="text-xs opacity-80">{team.captain}</div>
      </div>
    );
  };

  const MatchCard: React.FC<{ match: Match; showRound?: boolean }> = ({ match, showRound = false }) => (
    <div className="bg-white/20 rounded-lg p-4 mb-4">
      {showRound && (
        <div className="text-center text-blue-200 text-sm mb-2">
          {getRoundDisplayName(match.round)}
        </div>
      )}
      <div className="space-y-2">
        <TeamCard 
          team={match.team1} 
          isWinner={match.winner?.id === match.team1.id}
          isLoser={match.completed && match.winner?.id !== match.team1.id}
        />
        <div className="text-center text-white font-bold">VS</div>
        <TeamCard 
          team={match.team2} 
          isWinner={match.winner?.id === match.team2.id}
          isLoser={match.completed && match.winner?.id !== match.team2.id}
        />
      </div>
      {match.completed && (
        <div className="text-center text-green-300 text-sm mt-2">
          ✓ 获胜: {match.winner?.name}
        </div>
      )}
      {!match.completed && (
        <div className="text-center text-yellow-300 text-sm mt-2">
          ⏳ 进行中
        </div>
      )}
    </div>
  );

  const getRoundDisplayName = (round: string): string => {
    if (round === 'completed') return '比赛结束';

    if (tournamentConfig?.rounds) {
      const roundConfig = tournamentConfig.rounds.find(r => r.name === round);
      if (roundConfig) {
        return roundConfig.display_name;
      }
    }

    return round; // 如果找不到配置，返回原始名称
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 flex items-center justify-center">
        <div className="text-white text-xl">加载中...</div>
      </div>
    );
  }

  if (!tournamentState) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 flex items-center justify-center">
        <div className="text-center">
          <div className="text-white text-xl mb-4">比赛尚未开始</div>
          <button
            onClick={() => navigate('/tournament')}
            className="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg"
          >
            返回比赛管理
          </button>
        </div>
      </div>
    );
  }

  const round1Matches = getMatchesByRound('round1_main');
  const revivalMatches = getMatchesByRound('round1_revival');
  const round2Matches = getMatchesByRound('round2_main');
  const round3Matches = getMatchesByRound('round3_main');
  const finalMatches = getMatchesByRound('final');

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 p-4">
      <div className="max-w-7xl mx-auto">
        {/* 标题和导航 */}
        <div className="flex items-center justify-between mb-8">
          <button
            onClick={() => navigate('/tournament')}
            className="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded-lg"
          >
            ← 返回比赛管理
          </button>
          <h1 className="text-3xl md:text-4xl font-bold text-white">比赛对阵图</h1>
          <div className="w-32"></div> {/* 占位符保持居中 */}
        </div>

        {error && (
          <div className="bg-red-500/20 border border-red-500 text-red-100 px-4 py-3 rounded-lg mb-6">
            {error}
          </div>
        )}

        {/* 冠亚军展示 */}
        {tournamentState.current_round === 'completed' && (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
            {tournamentState.champion && (
              <div className="bg-yellow-500/20 border border-yellow-500 rounded-2xl p-6 text-center">
                <div className="text-4xl mb-4">🏆</div>
                <div className="text-2xl font-bold text-yellow-300 mb-2">冠军</div>
                <div className="text-xl font-semibold text-white">{tournamentState.champion.name}</div>
                <div className="text-blue-200">队长: {tournamentState.champion.captain}</div>
              </div>
            )}
            {tournamentState.runner_up && (
              <div className="bg-gray-500/20 border border-gray-500 rounded-2xl p-6 text-center">
                <div className="text-4xl mb-4">🥈</div>
                <div className="text-2xl font-bold text-gray-300 mb-2">亚军</div>
                <div className="text-xl font-semibold text-white">{tournamentState.runner_up.name}</div>
                <div className="text-blue-200">队长: {tournamentState.runner_up.captain}</div>
              </div>
            )}
          </div>
        )}

        {/* 对阵图 */}
        <div className="grid grid-cols-1 lg:grid-cols-5 gap-6">
          {/* 第一轮晋级赛 */}
          <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-4">
            <h3 className="text-lg font-bold text-white mb-4 text-center">第一轮晋级赛</h3>
            {round1Matches.map((match) => (
              <MatchCard key={match.id} match={match} />
            ))}
          </div>

          {/* 复活赛 */}
          <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-4">
            <h3 className="text-lg font-bold text-white mb-4 text-center">复活赛</h3>
            {revivalMatches.length > 0 ? (
              revivalMatches.map((match) => (
                <MatchCard key={match.id} match={match} />
              ))
            ) : (
              <div className="text-center text-blue-200">暂无比赛</div>
            )}
            {/* 轮空队伍 */}
            {getRevivalTeams().length > revivalMatches.length * 2 && (
              <div className="bg-white/20 rounded-lg p-4 mb-4">
                <div className="text-center text-blue-200 text-sm mb-2">轮空直接复活</div>
                <TeamCard
                  team={getRevivalTeams().find(team =>
                    !revivalMatches.some(match =>
                      match.team1.id === team.id || match.team2.id === team.id
                    )
                  ) || null}
                />
              </div>
            )}
          </div>

          {/* 第二轮晋级赛 */}
          <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-4">
            <h3 className="text-lg font-bold text-white mb-4 text-center">第二轮晋级赛</h3>
            {round2Matches.length > 0 ? (
              round2Matches.map((match) => (
                <MatchCard key={match.id} match={match} />
              ))
            ) : (
              <div className="text-center text-blue-200">暂无比赛</div>
            )}
          </div>

          {/* 第三轮晋级赛 */}
          <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-4">
            <h3 className="text-lg font-bold text-white mb-4 text-center">第三轮晋级赛</h3>
            {round3Matches.length > 0 ? (
              round3Matches.map((match) => (
                <MatchCard key={match.id} match={match} />
              ))
            ) : (
              <div className="text-center text-blue-200">暂无比赛</div>
            )}
          </div>

          {/* 决赛 */}
          <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-4">
            <h3 className="text-lg font-bold text-white mb-4 text-center">决赛</h3>
            {finalMatches.length > 0 ? (
              finalMatches.map((match) => (
                <MatchCard key={match.id} match={match} />
              ))
            ) : (
              <div className="text-center text-blue-200">暂无比赛</div>
            )}
          </div>
        </div>

        {/* 第一轮对战分组展示 */}
        {tournamentState.round1_groups && Object.keys(tournamentState.round1_groups).length > 0 && (
          <div className="mt-8 bg-white/10 backdrop-blur-sm rounded-2xl p-6">
            <h3 className="text-xl font-bold text-white mb-4 text-center">第一轮对战分组</h3>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {Object.entries(tournamentState.round1_groups).map(([groupName, teams]) => (
                <div key={groupName} className="bg-white/20 rounded-lg p-4">
                  <h4 className="text-lg font-semibold text-white mb-3 text-center">
                    {groupName}
                  </h4>
                  <div className="space-y-2">
                    {teams.map((team: any) => (
                      <TeamCard key={team.id} team={team} />
                    ))}
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default BracketPage;
